package com.gupaoedu.pattern.singleton.register;


import java.io.*;

/**
 * 2019/5/11
 * created by chenpp
 * 注册式单例 将单例以一个唯一标识注册到统一的容器上
 * 防止了由于反序列化破坏单例和通过反射破坏单例(Enum没有无参构造方法,而含参的构造方法在jdk层面就做了避免)
 */
public class RegisterSingletonTest {
//    public static void main(String[] args) {
//        try {
//            EnumSingleton instance1 = null;
//            EnumSingleton instance2 = EnumSingleton.EnumSingleton;
//            instance2.setData(new Object());
//            FileOutputStream fos = new FileOutputStream("EnumSingleton.obj");
//            ObjectOutputStream oos = new ObjectOutputStream(fos);
//            oos.writeObject(instance2);
//            oos.flush();
//            oos.close();
//            FileInputStream fis = new FileInputStream("EnumSingleton.obj");
//            ObjectInputStream ois = new ObjectInputStream(fis);
//            instance1 = (EnumSingleton) ois.readObject();
//            ois.close();
//            System.out.println(instance1==instance2);
//            //使用Data来做一个扩展,可以实现其他对象的单例
//            System.out.println(instance1.getData());
//            System.out.println(instance2.getData());
//            System.out.println(instance1.getData()==instance2.getData());
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//
//
//    }
//        public static void main(String[] args) {
//            try {
//                Class<?> clazz = EnumSingleton.class;
//                //获取无参/有参构造方法
//                Constructor constructor =  clazz.getDeclaredConstructor(String.class,int.class);
//                //私有方法 强吻
//                constructor.setAccessible(true);
//                Object instance = constructor.newInstance("enumSingleton",1);
//                System.out.psrintln(instance);
//                System.out.println(EnumSingleton.getInstance());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//        }
    public static void main(String[] args) {
            Object instance1 = null;
            Object instance2 = ContainerSingleton.getBean("com.gupaoedu.pattern.singleton.register.User");
        try{
            FileOutputStream fos = new FileOutputStream("ContainerSingleton.obj");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(instance2);
            oos.flush();
            oos.close();
            FileInputStream fis = new FileInputStream("ContainerSingleton.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
            instance1 = (User) ois.readObject();
            ois.close();
            System.out.println(instance1==instance2);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
